#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       dimcalc.py
#
#       Copyright 2010 vvs <skochko@gmail.com>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import gtk
import os
import sys
import math
import cairo
import accuracyclass
from dimension import *
from functions import *
from ConfigParser import ConfigParser

class Series_Dlg(gtk.Builder):
    '''
    Диалог добавления размерной цепи
    '''
    def __init__(self, parent, ser=None):
        super(Series_Dlg, self).__init__()
        self.par = parent
        self.add_from_file(os.path.join(os.path.dirname(__file__),
                                        'gui/series_dlg.ui'))
        if ser == None:
            self.series_name.set_editable(True)
            self.series_dialog.set_title('Добавление размерной цепи')
            self.add = True
        else:
            self.series_name.set_editable(False)
            self.add = False
            self.series_dialog.set_title('Редактирование размерной цепи')
            self.series_name.set_text(ser.name)
            self.series_note.set_text(ser.note)
        # подключаем обработчики сигналов
        self.connect_signals(self)


        # показываем окно и все виджеты на нем
        self.series_dialog.show_all()

    def __getattr__(self, attr):
        # удобней писать self.window1, чем self.get_object('window1')
        obj = self.get_object(attr)
        if not obj:
            raise AttributeError('object %r has no attribute %r' % (self,attr))
        setattr(self, attr, obj)
        return obj

    def on_add_series_button_clicked(self, widget):
        #print "add"
        if self.add:
            dim_series = DimSeries(self.series_name.get_text(), self.series_note.get_text())
            self.par.main_series.add_series(dim_series)
        else:
            print 'edit'
            self.par.current_dim_series.note = self.series_note.get_text()
            self.par.main_series.update(self.par.current_dim_series)
            #self.par.main_series.add_series(self.par.current_dim_series)
        #выполним обновление списка размерных цепей
        self.par.series_to_store()
        self.series_dialog.destroy()
        
    def on_close_btn_clicked(self, widget):
        self.series_dialog.destroy()

class Add_Dim_Dlg(gtk.Builder):
    '''
    Диалог добавления размера
    '''
    def __init__(self, parent):
        self.par = parent
        super(Add_Dim_Dlg, self).__init__()
        # загружаем
        self.add_from_file(os.path.join(os.path.dirname(__file__),
                                        'gui/add_dim_dlg.ui'))
        # подключаем обработчики сигналов
        self.connect_signals(self)
        self.completion = gtk.EntryCompletion()
        self.dim_value.set_completion(self.completion)
        self.liststore = gtk.ListStore(str)
        self.accuracyliststore = gtk.ListStore(str)
        self.accuracyclass.set_model(self.accuracyliststore)

        #accuracyclass.pack_start(cell, True)
        #accuracyclass.add_attribute(cell, 'text', 0)
        cell = gtk.CellRendererText()
        self.accuracyclass.pack_start(cell)
        self.accuracyclass.add_attribute(cell, 'text', 0)
        self.accuracyclass.set_wrap_width(5)
        self.accuracyliststore.append([''])
        for i in accuracyclass.accuracyclasses:
            self.accuracyliststore.append([i])
        self.completion.set_model(self.liststore)
        self.liststore.append(['10'])
        self.liststore.append(['12'])
        self.liststore.append(['15'])
        self.liststore.append(['20'])
        self.completion.set_text_column(0)
        a = []
        iter = self.liststore.get_iter_first()
        while iter != None:
            a.append(self.liststore.get_value(iter, 0))
            iter = self.liststore.iter_next(iter)
        # показываем окно и все виджеты на нем
        self.add_dim_dialog.show_all()

    def set_tolerance(self):
        '''
        Устанавливает значение верхнего и нижнего допусков в зависимости
        от введенного значения размера и выбранного квалитета
        '''
        try:
            tol = accuracyclass.get_tolerance(self.accuracyclass.get_active_text(),
                                             myfloat(self.dim_value.get_text()))
        except:
            tol = (0, 0)
        self.up_tolerance.set_text(mystr(tol[0], True, True))
        self.un_tolerance.set_text(mystr(tol[1], True, True))

    def on_accuracyclass_changed(self, event):
        self.set_tolerance()

    def on_dim_value_changed(self, event):
        self.set_tolerance()
        
    def on_tolerance_key_press_event(self, widget, event):
        self.accuracyclass.set_active(0)

    def on_plusminus_clicked(self, event):
        self.un_tolerance.set_text(mystr(-myfloat(self.up_tolerance.get_text()), True, True))

    def add_dim(self, oper):
        '''
        Если oper = '+' то добавляет размер в цепь
        Если oper = '-' то вычитает размер из цепи
        '''
        dim_name = self.dim_name.get_text()
        dim_note = self.dim_note.get_text()
        if dim_name != '':
            try:
                dim_value = myfloat(self.dim_value.get_text())
                up_tolerance = myfloat(self.up_tolerance.get_text())
                un_tolerance = myfloat(self.un_tolerance.get_text())
                accuracy = self.accuracyclass.get_active_text()
                dim = Dim(dim_name, dim_value, up_tolerance, un_tolerance, accuracy, dim_note)
                if oper == '+':
                    self.par.current_dim_series.add_dim(dim)
                elif oper == '-':
                    self.par.current_dim_series.sub_dim(dim)
                #обновим размеры в списке
                self.par.dim_to_store()
                #обновим формулу в текстовом поле
                self.par.entryf.set_text(self.par.current_dim_series.formula)
                #перерисуем размерную цепь
                self.par.drawingarea.queue_draw()
                self.dim_name.set_text(addnameind(dim_name))
            except:
                print "Неожиданная ошибка:", sys.exc_info()
        else:
            print 'Введите имя размера'

    def on_add_dim_button_clicked(self, widget):
        self.add_dim('+')

    def on_sub_dim_button_clicked(self, widget):
        self.add_dim('-')

    def __getattr__(self, attr):
        # удобней писать self.window1, чем self.get_object('window1')
        obj = self.get_object(attr)
        if not obj:
            raise AttributeError('object %r has no attribute %r' % (self,attr))
        setattr(self, attr, obj)
        return obj

    def on_dim_value_motion_notify_event(self, area, event):
        #print event.x, event.y
        #self.completion.set_popup_completion(True)
        pass


class Edit_Dim_Dlg(gtk.Builder):
    '''
    Диалог добавления размера
    '''
    def __init__(self, parent, dim):
        self.parent = parent
        self.dim = dim
        super(Edit_Dim_Dlg, self).__init__()
        # загружаем
        self.add_from_file(os.path.join(os.path.dirname(__file__),
                                        'gui/edit_dim_dlg.ui'))
        # подключаем обработчики сигналов
        self.connect_signals(self)
        self.accuracyliststore = gtk.ListStore(str)
        self.accuracyclass.set_model(self.accuracyliststore)

        #accuracyclass.pack_start(cell, True)
        #accuracyclass.add_attribute(cell, 'text', 0)
        cell = gtk.CellRendererText()        
        self.accuracyclass.pack_start(cell)
        self.accuracyclass.add_attribute(cell, 'text', 0)
        self.accuracyclass.set_wrap_width(10)
        self.accuracyliststore.append([''])
        ind = 0        
        for i in range(0, len(accuracyclass.accuracyclasses)):
            self.accuracyliststore.append([accuracyclass.accuracyclasses[i]])
            if accuracyclass.accuracyclasses[i] == self.dim.accuracy:
                ind = i + 1
        self.accuracyclass.set_active(ind)
        #загрузим информацию о размере
        self.dim_name.set_text(dim.name)
        self.dim_note.set_text(dim.note)
        self.dim_value.set_text(mystr(dim.value))
        self.up_tolerance.set_text(mystr(dim.up_tolerance))
        self.un_tolerance.set_text(mystr(dim.un_tolerance))
        
        # показываем окно и все виджеты на нем
        self.edit_dim_dialog.show_all()

    def set_tolerance(self):
        '''
        Устанавливает значение верхнего и нижнего допусков в зависимости
        от введенного значения размера и выбранного квалитета
        '''
        try:
            tol = accuracyclass.get_tolerance(self.accuracyclass.get_active_text(),
                                             myfloat(self.dim_value.get_text()))
        except:
            tol = (0, 0)
        self.up_tolerance.set_text(mystr(tol[0], True, True))
        self.un_tolerance.set_text(mystr(tol[1], True, True))

    def on_accuracyclass_changed(self, event):
        self.set_tolerance()

    def on_dim_value_changed(self, event):
        self.set_tolerance()
        
    def on_tolerance_key_press_event(self, widget, event):
        self.accuracyclass.set_active(0)

    def on_plusminus_clicked(self, event):
        self.un_tolerance.set_text(mystr(-myfloat(self.up_tolerance.get_text()), True, True))

    def on_edit_dim_button_clicked(self, widget):
        dim_note = self.dim_note.get_text()
        dim_value = myfloat(self.dim_value.get_text())
        up_tolerance = myfloat(self.up_tolerance.get_text())
        un_tolerance = myfloat(self.un_tolerance.get_text())
        accuracy = self.accuracyclass.get_active_text()
        dim = Dim(self.dim.name, dim_value, up_tolerance, un_tolerance, accuracy, dim_note)
        self.parent.main_series.update_dim(dim)
        self.parent.dim_to_store()
        self.edit_dim_dialog.destroy()

    def on_cancel_button_clicked(self, widget):
        self.edit_dim_dialog.destroy()

    def __getattr__(self, attr):
        # удобней писать self.window1, чем self.get_object('window1')
        obj = self.get_object(attr)
        if not obj:
            raise AttributeError('object %r has no attribute %r' % (self,attr))
        setattr(self, attr, obj)
        return obj


class DimCalc(gtk.Builder):

    def __init__(self):
        super(DimCalc, self).__init__()
        # загружаем
        self.add_from_file(os.path.join(os.path.dirname(__file__),
            'gui/dimcalc.ui'))
        self.dim_icon = gtk.gdk.pixbuf_new_from_file(os.path.join(
                        os.path.dirname(__file__),'images/dim.png'))
        self.series_icon = gtk.gdk.pixbuf_new_from_file(os.path.join(
                        os.path.dirname(__file__),'images/series.png'))
        self.main_series = MainSeries()
        self.__current_dim_series = self.main_series.series[0]
        self.entryf.set_text(self.current_dim_series.formula)
        self.alldim_view.drag_source_set(gtk.gdk.BUTTON1_MASK | gtk.gdk.BUTTON3_MASK,  [( "text/plain", 0, 80 )],
                               gtk.gdk.ACTION_COPY)
        self.drawingarea.drag_dest_set(gtk.DEST_DEFAULT_MOTION |
                                  gtk.DEST_DEFAULT_HIGHLIGHT |
                                  gtk.DEST_DEFAULT_DROP,
                                  [ ( "text/plain", 0, 80 ) ],
                                  gtk.gdk.ACTION_COPY)
        # подключаем обработчики сигналов
        self.connect_signals(self)
        self.create_columns(self.series_view)
        self.create_columns(self.dim_view)
        self.alldim_create_columns(self.alldim_view)
        self.dim_to_store()
        self.series_to_store()

        self.alldim_view.enable_model_drag_dest([('text/plain', 0, 0)],
                gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_MOVE)
        # показываем окно и все виджеты на нем
        self.main_window.show_all()

    def __getattr__(self, attr):
        # удобней писать self.window1, чем self.get_object('window1')
        obj = self.get_object(attr)
        if not obj:
            raise AttributeError('object %r has no attribute %r' % (self,attr))
        setattr(self, attr, obj)
        return obj

    @property
    def current_dim_series(self):
        return self.__current_dim_series

    @current_dim_series.setter
    def current_dim_series(self, current_dim_series):
        self.__current_dim_series = current_dim_series
        self.entryf.set_text(current_dim_series.formula)
        # перерисуем размерную цепь
        self.drawingarea.queue_draw()

    def create_columns(self, treeView):
        '''
        Метод отвечает за создание колонок для грида.
        '''
        rendererPixbuf = gtk.CellRendererPixbuf()
        column = gtk.TreeViewColumn("", rendererPixbuf, pixbuf=0 )
        column.set_sort_column_id(0)
        treeView.append_column(column)

        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn("Имя", rendererText, text=1)
        column.set_sort_column_id(1)
        treeView.append_column(column)

        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn("Значение", rendererText, text=2)
        column.set_sort_column_id(2)
        treeView.append_column(column)

        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn("Примечание", rendererText, text=3)
        column.set_sort_column_id(3)
        treeView.append_column(column)

    def alldim_create_columns(self, treeView):
        rendererPixbuf = gtk.CellRendererPixbuf()
        column = gtk.TreeViewColumn("", rendererPixbuf, pixbuf=0 )
        column.set_sort_column_id(0)
        treeView.append_column(column)

        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn("Размер", rendererText, text=1)
        column.set_sort_column_id(1)
        treeView.append_column(column)


    def dim_to_store(self):
        self.dim_liststore.clear()
        for dim_name, dim in self.current_dim_series.dimensions.items():
            self.dim_liststore.append([self.dim_icon, dim_name,
                                        str(dim), dim.note])
        self.alldim_to_store()

    def alldim_to_store(self):
        self.alldim_liststore.clear()
        for dim_name, dim in self.main_series.dimensions.items():
            self.alldim_liststore.append([self.dim_icon, dim_name])
        #for dim_name, dim in self.current_dim_series.dimensions.items():
        #    self.alldim_liststore.append([self.dim_icon, dim_name])
        for ser in self.main_series.series:
            if ser.name != self.current_dim_series.name:
                self.alldim_liststore.append([self.series_icon, ser.name])

    def series_to_store(self):
        self.series_liststore.clear()
        for series in self.main_series.series:
            self.series_liststore.append([self.series_icon, series.name,
                                         str(series), series.note])

    def update_series_store(self):
        '''
        Обновляет выделенный элемент списка размерных цепей
        '''
        tree_model = self.series_view.get_model()

        #self.store.set(tree_iter, 1, title, 2, genre, 3, date, 4, viewed)
        iter = tree_model.get_iter_first()
        while iter != None:
            name = tree_model.get_value(iter, 1)
            series = self.main_series.get_series(name)
            self.series_liststore.set(iter, 1, series.name, 2, str(series), 3, series.note)
            iter = tree_model.iter_next(iter)
        #if tree_iter != None:
        #    self.series_liststore.set(tree_iter, 1, series.name, 2, str(series), 3, '')

    def on_open_file_btn_clicked(self, widget):
        '''
        Показывает диалог открытия файла
        '''
        dialog = gtk.FileChooserDialog("Открытие файла размерных цепей", None,
                                      gtk.FILE_CHOOSER_ACTION_OPEN,
                                      (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                      gtk.STOCK_OPEN, gtk.RESPONSE_OK)
                                     )
        filter = gtk.FileFilter()
        filter.set_name("Файлы размерных цепей")
        filter.add_mime_type("dimcalc")
        filter.add_pattern("*.p15")
        dialog.add_filter(filter)
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            if sys.platform == 'win32':
                filename = dialog.get_filename().encode('cp1251')
            else:
                filename = dialog.get_filename()
            self.main_series.load_from_file(filename)
            self.series_to_store()
            self.dim_to_store()
            #self.alldim_to_store()
            self.current_dim_series = self.main_series.series[0]
        #    font_desc = pango.FontDescription(fdia.get_font_name())
        #    if font_desc:
        #        self.label.modify_font(font_desc)
        dialog.destroy()

    def on_save_file_btn_clicked(self, widget):
        '''
        Сохраняет файл, при необходимости показывает диалог сохранения файла
        '''
        if self.main_series.save_as:
            self.on_saveas_btn_clicked(widget)
        else:
            self.main_series.save_to_file()

    def on_saveas_btn_clicked(self, widget):
        '''
        Показывает диалог сохранения файла
        '''
        dialog = gtk.FileChooserDialog("Сохранить файл размерных цепей", None,
                                      gtk.FILE_CHOOSER_ACTION_SAVE,
                                      (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                      gtk.STOCK_SAVE, gtk.RESPONSE_OK)
                                     )
        filter = gtk.FileFilter()
        filter.set_name("Файлы размерных цепей")
        filter.add_mime_type("dimcalc")
        filter.add_pattern("*.p15")
        dialog.add_filter(filter)
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            filename = dialog.get_filename()
            if filename[len(filename)-4:] != '.p15':
                filename += '.p15'
            if sys.platform == 'win32':
                filename = filename.encode('cp1251')
            self.main_series.save_to_file(filename)
        #    font_desc = pango.FontDescription(fdia.get_font_name())
        #    if font_desc:
        #        self.label.modify_font(font_desc)
        dialog.destroy()


    def on_drawingarea_expose_event(self, widget, event):
        '''
        Рисуем размерную цепь
        '''
        x, y, width, height = widget.get_allocation()

        i = 1
        arrow_size = 20
        offset = 50            #отступ для рисунка
        text_offset = 10       #отступ для текста
        start_y = offset

        #Преобразуем формулу в массив размеров
        formula = self.current_dim_series.formulax
        if formula != '':
            formula = formula.replace(' + ', '|')
            formula = formula.replace(' - ', '|-')
            formula = formula.split('|')
            #определим длинновые габариты цепи
            l = 0
            max = 0
            min = 0
            for cell in formula:
                dim = eval(cell)
                l += dim.value
                if l >= max:
                    max = l
                if l < min:
                    min = l
            l = abs(max) + abs(min)
            #определим масштаб, растояние между размерами
            distance = (height - offset*2) // len(formula)
            if l != 0:
                scale = (width - 2 * offset) // l
            else:
                scale = 1
            x = abs(min) * scale + offset
            start_x = x
            y = start_y

        #рисуем
        cr = widget.window.cairo_create()
        #фон для рисования
        lg3 = cairo.LinearGradient(0, 0,  0, height)
        lg3.add_color_stop_rgba(0.1, 1, 1, 1, 1)
        #lg3.add_color_stop_rgba(0.9, 0.7, 0.7, 0.93, 1)
        lg3.add_color_stop_rgba(0.9, 0.94, 0.85, 0.51, 1)
        cr.rectangle(0, 0, width, height)
        cr.set_source(lg3)
        cr.fill()
        #цвет линий для рисования размеров
        cr.set_source_rgb(0, 0, 1)
        cr.set_line_width(2)
        #шрифт для надписей
        cr.select_font_face("Ubuntu", cairo.FONT_SLANT_NORMAL,
            cairo.FONT_WEIGHT_NORMAL)
        if len(formula) > 0:
            for cell in formula:
                dim = eval(cell)
                #if dim.value < 0:
                #    dim.up_tolerance = -dim.up_tolerance
                #    dim.un_tolerance = -dim.un_tolerance
                end_x = int(x+scale*dim.value)
                #end_y = y + int(distance*scale)
                end_y = y + distance
                cr.move_to(x, y)
                cr.line_to(end_x, y)
                cr.move_to(end_x, y)
                cr.line_to(end_x, end_y)
                cr.stroke()
                #стрелки
                if dim.value >= 0:
                    cr.move_to(end_x-arrow_size, y-arrow_size//4)
                    cr.line_to(end_x, y)
                    cr.line_to(end_x-arrow_size, y+arrow_size//4)
                    cr.line_to(end_x-arrow_size, y-arrow_size//4)
                    cr.fill()
                else:
                    cr.move_to(end_x+arrow_size, y-arrow_size//4)
                    cr.line_to(end_x, y)
                    cr.line_to(end_x+arrow_size, y+arrow_size//4)
                    cr.line_to(end_x+arrow_size, y-arrow_size//4)
                    cr.fill()
                #Значение размера
                cr.set_font_size(20)
                te = cr.text_extents(mystr(abs(dim.value))+'1')
                x_text = (x+(end_x-x)//2)-te[2]//2
                y_text = y-text_offset
                value_width = te[2]                     #ширина текста
                value_height = te[3]                    #высота текста
                cr.move_to(x_text, y_text)
                cr.show_text(mystr(abs(dim.value)))
                #Рисуем допуска
                cr.set_font_size(15)
                te = cr.text_extents(mystr(dim.up_tolerance, True))
                tol_width = te[2]                       #ширина текста допуска
                tol_height = te[3]                      #высота текста допуска
                cr.move_to(x_text+value_width, y_text-value_height+tol_height//2)
                cr.show_text(mystr(dim.up_tolerance, True))
                cr.move_to(x_text+value_width, y_text+tol_height//2)
                cr.show_text(mystr(dim.un_tolerance, True))
                x = end_x
                y = end_y
            cr.set_source_rgb(1, 0, 0)
            cr.move_to(end_x, end_y)
            cr.line_to(start_x, end_y)
            cr.line_to(start_x, start_y)
            cr.stroke()
            #стрелки
            if self.current_dim_series.value < 0:
                cr.move_to(start_x-arrow_size, end_y-arrow_size//4)
                cr.line_to(start_x, end_y)
                cr.line_to(start_x-arrow_size, end_y+arrow_size//4)
                cr.line_to(start_x-arrow_size, end_y-arrow_size//4)
            else:
                cr.move_to(start_x+arrow_size, end_y-arrow_size//4)
                cr.line_to(start_x, end_y)
                cr.line_to(start_x+arrow_size, end_y+arrow_size//4)
                cr.line_to(start_x+arrow_size, end_y-arrow_size//4)
            cr.fill()
            cr.stroke()
            #Значение размера
            cr.set_font_size(20)
            te = cr.text_extents(mystr(abs(self.current_dim_series.value))+'1')
            x_text = (start_x+(end_x-start_x)//2)-te[2]//2
            y_text = y-text_offset
            value_width = te[2]                     #ширина текста
            value_height = te[3]                    #высота текста
            cr.move_to(x_text, y_text)
            cr.show_text(mystr(abs(self.current_dim_series.value)))
            #Рисуем допуска
            cr.set_font_size(15)
            te = cr.text_extents(mystr(self.current_dim_series.up_tolerance, True))
            tol_width = te[2]                       #ширина текста допуска
            tol_height = te[3]                      #высота текста допуска
            cr.move_to(x_text+value_width, y_text-value_height+tol_height//2)
            cr.show_text(mystr(self.current_dim_series.up_tolerance, True))
            cr.move_to(x_text+value_width, y_text+tol_height//2)
            cr.show_text(mystr(self.current_dim_series.un_tolerance, True))
        return False

    def on_main_window_destroy(self, event):
        gtk.main_quit()

    def on_series_view_cursor_changed(self, event):
        '''
        Событие при выборе размерной цепи
        '''
        #определим имя выбранной размерной цепи
        tree_model, tree_iter = self.series_view.get_selection().get_selected()
        try:
            seriesName = tree_model.get_value(tree_iter, 1)
        except:
            seriesName = ''
        if seriesName != '':
            #сохраним изменения сделанные в текущей размерной цепи
            #self.current_dim_series.formula = self.entryf.get_text()
            #self.main_series.update(self.current_dim_series)
            self.current_dim_series = self.main_series.get_series(seriesName)
            self.entryf.set_text(self.current_dim_series.formula)
            #Обновим список размеров
            self.dim_to_store()
            #перерисуем размерную цепь
            self.drawingarea.queue_draw()

    def on_entryf_changed(self, event):
        #создадим временную размерную цепь для проверки формулы
        tmp_series = self.current_dim_series
        #добавим необходимые размеры в размерную цепь
        formula = self.entryf.get_text()
        for dim_name, dim in self.main_series.dimensions.items():
            if dim_in_formula(formula, dim_name):
                tmp_series.add(dim)
        #добавим вычисленные размеры в цепь
        for ser in self.main_series.series:
            if dim_in_formula(formula, ser.name):
                tmp_series.add(ser.name, str(ser), ser.note)
        #Проверим вычисление формулы
        try:
            tmp_series.formula = self.entryf.get_text()
        except:
            self.entryf.modify_text(gtk.STATE_NORMAL, gtk.gdk.Color('#ff0000'))
            self.statusbar.push(0, "Ошибка:"+str(sys.exc_info()[1]))
        else:
            #если все нормально то применим формулу к текущей размерной цепи
            self.entryf.modify_text(gtk.STATE_NORMAL, gtk.gdk.Color('#000000'))
            self.current_dim_series = tmp_series
            print 'self.current_dim_series', str(self.current_dim_series)
            self.main_series.update(self.current_dim_series)
            self.statusbar.push(0, '')

            #Обновим размерную цепь в списоке размерных цепей
            self.update_series_store()
            #Перересуем размерную цепь
            self.drawingarea.queue_draw()

    def on_add_dim_series_clicked(self, widget):
        '''
        Показать диалог добавления размерной цепи
        '''
        add_series_dlg = Series_Dlg(self)

    def on_add_dim_dlg_button_clicked(self, widget):
        '''
        Показывает диалог добавления размера
        '''
        add_dim_dlg = Add_Dim_Dlg(self)

    def on_show_about_activate(self, widget):
        logo = gtk.gdk.pixbuf_new_from_file(os.path.join(os.path.dirname(__file__), 'images/dimcalc.png'))
        #print 'logo_file =',os.path.join(os.path.dirname(__file__), 'images/dimcalc.png')
        about = gtk.AboutDialog()
        about.set_name('DimCalc')
        about.set_version('0.1 alpha')
        about.set_copyright('(c) 2011 vvs Victor Skochko')
        about.set_comments('Программа для выполнения размерного расчета')
        #about.set_license(license)
        #about.set_wrap_license(license)
        about.set_website('http://code.google.com/p/dimcalc')
        #about.set_website_label(website_label)        
        about.set_authors(('P@tron (Дмитрий Зайцев - тестирование программы)',))
        #about.set_documenters(documenters)
        #about.set_artists(artists)
        #about.set_translator_credits(translator_credits)
        about.set_logo(logo)
        #about.set_logo_icon_name(icon_name)
        about.set_program_name('DimCalc')
        about.show_all()
        response = about.run()
        about.destroy()

    def on_alldim_view_drag_data_get(self, widget, context, selection, targetType, eventTime):

        tree_model, tree_iter = self.alldim_view.get_selection().get_selected()
        try:
            dim_name = tree_model.get_value(tree_iter, 1)
        except:
            dim_name = ''
        selection.set(selection.target, 8, dim_name)

    def on_alldim_view_drag_begin(self, drag_context, data):
        tree_model, tree_iter = self.alldim_view.get_selection().get_selected()
        path = self.alldim_liststore.get_path(tree_iter)
        pixmap = self.alldim_view.create_row_drag_icon(path)
        drag_context.drag_source_set_icon(pixmap.get_colormap(),pixmap)

    def on_drawingarea_drag_data_received(self, widget, context, x, y, selection,
                                          targetType, time):
        if self.entryf.get_text() != '':
            self.entryf.set_text(self.entryf.get_text() + ' + '+ selection.data)
        else:
            self.entryf.set_text('+'+ selection.data)

    def on_series_view_button_press_event(self, widget, event):
        '''
        Событие при двойном нажатии на элемент в списке размеров
        '''
        if event.type == gtk.gdk._2BUTTON_PRESS:
            ser_dlg = Series_Dlg(self, self.current_dim_series)
            
    def on_dim_view_button_press_event(self, widget, event):
        '''
        Событие при двойном нажатии на элемент в списке размеров
        '''
        #определим имя выбранного размера
        tree_model, tree_iter = self.dim_view.get_selection().get_selected()
        try:
            dim_name = tree_model.get_value(tree_iter, 1)
        except:
            dim_name = ''
        if event.type == gtk.gdk._2BUTTON_PRESS:
            if dim_name != '':
                dim = self.main_series.get_dim(dim_name)
                edit_dim_dlg = Edit_Dim_Dlg(self, dim)

            
    def on_new_file_btn_clicked(self, widget):
        '''
        Собыите при нажатии кнопки создания нового файла
        '''
        self.main_series = None
        self.main_series = MainSeries()
        self.series_to_store()
        self.alldim_to_store()
        self.current_dim_series = self.main_series.x1

if __name__ == '__main__':
    dimcalc = DimCalc()

    gtk.main()


